package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Component
public class RedisIdWorker {
    //开始的时间戳
    private static final long BEGIN_TIMESTAMP=1735689600;
    private static final long COUNT_BITS=32;
    private StringRedisTemplate stringRedisTemplate;
    public RedisIdWorker(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate=stringRedisTemplate;
    }

    public long nextId(String keyPrefix){
        LocalDateTime now = LocalDateTime.now();
        //生成当前的时间戳
        long epochSecond = now.toEpochSecond(ZoneOffset.UTC);
        long time_stamp=epochSecond-BEGIN_TIMESTAMP;
        Long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + time_stamp);
        return epochSecond<<COUNT_BITS|increment;
    }
}
